#include <iostream>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

int ans = 0;
int deepth(TreeNode* root){
    if(!root) return 0;
    int l = deepth(root->left);
    int r = deepth(root->right);
    ans = max(ans, l+r);
    return 1 + max(l,r);
}

int diameterOfBinaryTree(TreeNode* root) {
    deepth(root);
    return ans;
}